import { isObject } from "/@/utils/is"
import { forIn } from "lodash"

/**
 * 获取对象的值
 * @param obj 对象
 * @param keys 值, 嵌套对象, 以 . 分割
 * @returns
 */
export function getObjValue(obj, keys) {
  let value = obj
  keys.split(".").forEach((key) => {
    if (!value?.hasOwnProperty(key)) {
      value = null
      return
    }
    value = value[key]
  })
  return value
}

/**
 * 删除对象中的key
 * @param obj 对象
 * @param keysToDelete 删除的key, 可以指定多层对象中的某个key, 用 . 分割key
 * @returns
 */
export function deleteObjKey(obj, keysToDelete) {
  const keys = keysToDelete.split(".")

  if (keys.length === 1) {
    delete obj[keys[0]]
    return
  }

  const currentKey = keys.shift()
  deleteObjKey(obj[currentKey], keys.join("."))
}

/**
 * 往对象中添加键值对
 * @param obj 对象
 * @param keys 添加的key, 支持多个key, 使用点分割
 * @param value 对应的值
 */
export function addValueToObj(obj, keys, value) {
  const keyArr = keys.split(".")
  const lastKey = keyArr.pop()

  let nestedObj = obj
  for (const key of keyArr) {
    if (!nestedObj[key]) {
      nestedObj[key] = {}
    }
    nestedObj = nestedObj[key]
  }

  nestedObj[lastKey] = value
}

export const overwriteObj = function (obj1, obj2) {
  /* 浅拷贝对象属性，obj2覆盖obj1 */
  Object.keys(obj2).forEach((prop) => {
    obj1[prop] = obj2[prop]
  })
}

/**
 * 嵌套对象key扁平化
 */
export const nestedObjectKeyToStr = (obj) => {
  const newObj = { ...obj }
  for(const key in obj) {
    if (!isObject(obj[key])) {
      continue
    }
    for(const subObjectKey in obj[key]) {
      newObj[key + '_' + subObjectKey] = obj[key][subObjectKey]
    }
  }
  return newObj
}

/**
 * 江嵌套对象的key字符串转成对象
 */
export const getNestedObjectKeyStrToObj = (obj) => {
  const newObj = { ...obj }
  for(const key in obj) {
    if (key.includes('_')) {
      console.log('key', key, )
      const subObjKey = key.split('_')[0]
      const subObjKey2 = key.split('_')[1]
      newObj[subObjKey] = newObj[subObjKey] || {}
      newObj[subObjKey][subObjKey2] = newObj[key]
      console.log('key', key, newObj[key])
      delete newObj[key]
    }
  }
  return newObj
}
